package com.lin.generate.common.utill;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
/**
 * @description TODO
 * @Author: z156940l@outlook.com
 * @className CookieUtils
 * @Date: 2023/6/1 23:37
 */
public class CookieUtils {
    /**
     * 根据cookieName获取cookie中的json web token
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static JWT getJwt(HttpServletRequest request, String cookieName) {
        JWT jwt = null;
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    if (cookie.getName().equals(cookieName)) {
                        String token = cookie.getValue();
                        jwt = JsonWebToken.checkToken(token);
                        break;
                    }
                }
            } else {
                String token = request.getHeader(JsonWebToken.COOKIE_NAME);
                if (StringUtils.isNotBlank(token)) {
                    jwt = JsonWebToken.checkToken(token);
                }
            }
        }

        return jwt;
    }
}
